// packageF/goods-packge/index.js
import tool from "../../utils/util";
let app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    pid: 0,
    scrollArr: [],
    package_id:null,
    isScroll: false,
    order_active: 0,
    total: 0,
    title: "",
    share_title: "",
    share_thumb: "",
    share_desc: "",
    description_title: "",
    description_thumb: "",
    description_desc: "",
    order_list: [],
    checkAll: false,
    carousels: [],
    on_sale_price: 0,
    salePrice:0,
    end_time:0,
    end_time_obj:{},
    time_over:false,//倒计时结束
    isDiscount:false,//是否优惠价格
    other_packages:[],
    goodsIdsArr:[], //优惠价格的数组
    loadingHidden:false,
    page_template: 0,
    isFixedShow:false,
    popupSpecs:false,
    cartList:[],
    getGoods:{},
    Hei:'',
    imgheights:[],
    imgBoxSize:'',
    imgPath: app.globalData.imgPath,
  },
  getTotal() {
    // 获取商品列表的高度
    let arr = this.data.carousels.length > 0 ? [260] : [60];
    arr[0] += this.data.time_over?80:0;  //倒计时是否显示，显示就加
    let query = wx.createSelectorQuery();
    let bool = false;
    query.select(".info").boundingClientRect(res => {
      if (!bool && res) {
        arr[0] += res.height;
        bool = true;
      }
     
    }).exec();
   
    query.selectAll(".list-item").boundingClientRect((res) => {
      res.forEach((item, i) => {
        arr[i + 1] = arr[i] + item.height + 10;
      });
    }).exec();
    this.setData({ scrollArr: arr });
  },
  imgH(e){
    var winWid = wx.getSystemInfoSync().windowWidth;//获取当前屏幕的宽度
    var imgh=e.detail.height;//图片高度
    var imgw=e.detail.width;
    var swiperH=winWid*imgh/imgw;　//等比设置swiper的高度。  即 屏幕宽度 / swiper高度 = 图片宽度 / 图片高度    ==》swiper高度 = 屏幕宽度 * 图片高度 / 图片宽度
    this.data.imgheights.push(swiperH);
    this.data.imgBoxSize = Math.max.apply(null, this.data.imgheights);
    this.setData({
        Hei:`${this.data.imgBoxSize}px`//设置高度
    })
  },
  count_down({detail:{days,hours,seconds,minutes}}){
    //倒计时时间'
    let end_time_obj = {
      days,
      hours:hours>=10?hours:"0" + hours,
      seconds:seconds>=10?seconds:"0" + seconds,
      minutes:minutes>=10?minutes:"0" + minutes
    }
    this.setData({end_time_obj});
  },
  tabsChange: tool.throttle(function (msg) {//滚动效果
    let data = msg[0];
    let isFixed = data.detail.isFixed;
    this.setData({
      isFixedShow:isFixed
    })
  },50),
  goodsSpescOn(event) {
    let goodsitem = event.currentTarget.dataset.goodsitem;
    this.setData({
      getGoods:goodsitem,
      popupSpecs:true
    })
  },
  close_yz_specs_popup(event) {
    let {clicktype,goodsCount,optionsId} = event.detail;
    this.setData({
      popupSpecs: false,
    });
    if (clicktype == 1) {
      //点击确认按钮
      this.data.order_list.forEach((item,index) => {
        item.goods_list.forEach((goodsItem,goodsIndex) => {
          goodsItem.has_many_options.forEach((optionItem,optionIndex) => {
            if(optionItem.id === optionsId) {
              this.setData({
                [`order_list[${index}].goods_list[${goodsIndex}].stock`]:optionItem.stock,
                [`order_list[${index}].goods_list[${goodsIndex}].count`]:goodsCount,
                [`order_list[${index}].goods_list[${goodsIndex}].optionsId`]:optionsId,
                [`order_list[${index}].goods_list[${goodsIndex}].price`]:optionItem.product_price,
                [`order_list[${index}].goods_list[${goodsIndex}].optionName`]:optionItem.title,
              })
            }
          })
        })
      });
    }
  },
  finish(){
    //倒计时结束
    this.setData({time_over:false});
    this.totalPrice();//重新计算价格
  },
  onPageScroll({ scrollTop }) {
    if (!this.data.isScroll) {
      // 滚动条事件，判断是否是点击触发的滚动条事件，不是的话就执行
      this.data.scrollArr.forEach((res, i) => {
        if (scrollTop > res - 10 && scrollTop < res + 10) {
          this.setData({ order_active: i });
        } else if (scrollTop < this.data.scrollArr[i + 1] - 100 && scrollTop > res) {
          this.setData({ order_active: i });
        }
      });
    }
  },
  link({ currentTarget }) {
    // 点击轮播图跳转
    let url = currentTarget.dataset.item.carousel_link;
    wx.navigateTo({ url });
  },
  change({ detail }) {
    this.setData({ isScroll: true});
    let scrollTop = this.data.scrollArr[detail.index];
    wx.pageScrollTo({
      scrollTop,
      duration: 300
    });
    setTimeout(() => {
      this.setData({ isScroll: false});
    }, 330);
    
  },
  settlement() {
    let _cart_ids = [];
    let goodBol = true;
    let json = {goods_list:[], package_id:this.data.package_id};
    let {order_list} = this.data;
    for (let i = 0; i < order_list.length; i++) {
      let item = order_list[i];
      for (let j = 0; j < item.goods_list.length; j++) {
        let items =  item.goods_list[j];
        if (items.check) {
          // let len = items.check_spe.reduce((pre, cur) => {
          //   return (cur >= 0) ? (pre + 1) : pre;
          // }, 0); // (注：这个页面应该还存在其他bug，修改时需要看一下h5的逻辑)
          if (items.has_option==1 && !items.optionsId && items.has_many_specs.length > 0) {
            goodBol = false;
            // app.tips(`商品：${items.title}规格属性未选择`);
          }
          _cart_ids.push(items.id);
          json.goods_list.push({
            goods_id:items.id,total:items.count,option_id:items.optionsId || ""
          });
        }
      }
    }
    if(!goodBol) {
      app.tips(`请选择商品规格`)
      return false;
    }
    if (_cart_ids.length<=0) return app.tips(`请选择结算商品`);
    wx.navigateTo({
      url: '/packageD/buy/myOrder_v2/myOrder_v2?tag=packagBuy&goods_ids='+JSON.stringify(_cart_ids)+'&packagJson='+JSON.stringify(json) 
    });
  },
  totalPrice() {
    //计算总价格
    let total = 0;
    let order_list = this.data.order_list;
    let len = 0;
    order_list.forEach(item => {
      let isCheck = false;
      item.goods_list.forEach(items => {
        if (items.check) isCheck = true;
        total += items.check ? items.price * items.count : 0;
      });
      if(isCheck) len = len+1;
    });
    if (len==order_list.length&&this.data.time_over) {
      let num = total- Number(this.data.on_sale_price);
      total = num<0?0:num;
      
      this.setData({isDiscount:true});
    }else {
      this.setData({isDiscount:false});
      if(this.data.salePrice) {
        let saleNum = total- Number(this.data.salePrice);
        total = saleNum<0?0:saleNum;
      }
    }
    
    total = total.toFixed(2);
    this.setData({ total });

  },
  async shopChange({ target, detail }) {
    let goodsIdsArr = [];
    let { i, c_index, count } = target.dataset;
    let { order_list } = this.data;
    let obj = order_list[i].goods_list[c_index];
    if (!count) obj.check = !obj.check;
    else obj.count = detail;
    for(let j in order_list) {
      for(let k in order_list[j].goods_list) {
        if(order_list[j].goods_list[k].check) {
          goodsIdsArr.push(order_list[j].goods_list[k].id)
        }
      }
    }
    this.setData({ order_list,goodsIdsArr });
    await this.getSalePrice();
    this.totalPrice();
  },
  gopackgoods(event){
    let {id,type} = event.currentTarget.dataset;
    //其他套餐
    if(type === 1) {
      wx.navigateTo({
        url: `/mircoApp/giftPackage/giftIndex/giftIndex?id=${id}`
      });
    } else {
      this.setData({loadingHidden:false});
      this.getdata(id);
      wx.pageScrollTo({
        scrollTop:0,
        duration: 0
      });
    }
    
  },
  getdata(package_id) {
    let url = app.getNetAddresss("plugin.goods-package.frontend.package.package.index");
    app._postNetWork({
      showToastIn: false,
      url,
      data: { package_id },
      success: ({ data }) => {
        if (data.result) {
          let { categories, title, description_thumb, description_title, description_desc, carousels, on_sale_price ,end_time,share_title,share_desc,share_thumb,limit_time_status,other_packages,page_template} = data.data;
          let order_list = categories.map(res => {
            res.goods_list.map(item => {
              item.count = 1;
              item.check = page_template?true: false;
              item.check_spe = [];
              item.price = item.price;
              item.optionsId = page_template&&item.has_option==1 && item.has_many_options[0]?item.has_many_options[0].id: 0
              return item;
            });
            return res;
          });
          end_time = (end_time-parseInt(new Date().getTime() / 1000))*1000;
          this.setData({ title, description_thumb, order_list, description_title, description_desc, carousels, 
            on_sale_price ,end_time,package_id,share_title,share_desc,share_thumb,time_over:limit_time_status==1?true:false,other_packages,loadingHidden:true,page_template});
          this.getTotal();
        } else {
          wx.showToast({
            icon: "none",
            title: data.msg,
            duration: 1500,
          });
        }
      }
    });
  },
  async getSalePrice() {
    let url = app.getNetAddresss("plugin.goods-package.frontend.package.package.get-sale-price");
    let res = await app._postNetWork({
      showToastIn: false,
      url,
      data: { 
        package_id:this.data.pid,
        goods_ids:this.data.goodsIdsArr
       },
    });

    if (res.data.result == 1) {
      let data = res.data.data;
      this.setData({
        salePrice:data.on_sale_price
      })
    } else {
      wx.showToast({
        icon: "none",
        title: res.data.msg,
        duration: 1500,
      });
    }
    
  },
  todetail({ currentTarget }) {
    if(this.data.page_template) return;
    //商品详情
    wx.navigateTo({
      url: "/packageA/detail_v2/detail_v2?id=" + currentTarget.dataset.id
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function ({ pid }) {
    this.setData({
      pid: pid
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getdata(this.data.pid);
    // this.getSalePrice(this.data.pid);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var value = wx.getStorageSync("yz_uid");
    var mid = "";
    if (value) {
      mid = value;
    }
    return {
      path: "/packageF/packageGoodse/packageGoods?pid=" + this.data.package_id + "&mid=" + mid,
      title: this.data.share_title,
      imageUrl: this.data.share_thumb,
    };
  }
});